﻿using NT.MES.Service;
using NT.MES.Service.Abstracts.Dto;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Test.DAL.Abstracts.ApplicationFeature;
using Test.DAL.Abstracts.ApplicationFeature.Entities;
using Test.Domain.Entities;
using Test.Service.Abstracts;
using Test.Service.Abstracts.ApplicationFeature;
using Test.Service.Abstracts.ApplicationFeature.Dtos;
using Test.Service.Abstracts.ApplicationFeature.EventData;
using TianShu.Domain;
using TianShu.Domain.Repositories;
using TianShu.EventBus.Distributed;
using TianShu.MultiTenancy;
using TianShu.Office;
using TianShu.Office.Abstractions;
using TianShu.Service.Dtos;
using TianShu.Service.Services.Crud;
using TianShu.SqlSugarCore.SqlSugarFactory;
using TianShu.Uow;

namespace Test.Service.ApplicationFeature
{
    public class ApplicationServiceImpl : CrudServiceImpl<EAMApplicationEntity, Guid, ApplicationListOutput, ApplicationCreateUpdateInput>, IApplicationService
    {
        public IApplicationDal ApplicationDAL { get; set; }
        public IDistributedEventBus _distributedEventBus { get; set; }

        public IRepository<EAMResourceTypeEntity, Guid> ResourceTypeRepository => LazyServiceProvider.LazyGetRequiredService<IRepository<EAMResourceTypeEntity, Guid>>();
        public IExcelService _excelService;

        public ApplicationServiceImpl(IApplicationDal appDal, IDistributedEventBus distributedEventBus, IExcelService excelService)
        {
            ApplicationDAL = appDal;
            _distributedEventBus = distributedEventBus;
            _excelService = excelService;
        }
        public override async Task<PageResultDto<IEnumerable<ApplicationListOutput>>> GetUrlParamAsync(List<UrlParams> urlParams)
        {
            return await base.GetUrlParamAsync(urlParams);
        }

        /// <summary>
        /// 工作单元测试
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [UnitOfWork]
        public override async Task<PageResultDto<ApplicationListOutput>> InsertAsync(ApplicationCreateUpdateInput dto)
        {
            await ResourceTypeRepository.InsertAsync(new EAMResourceTypeEntity { Code = "111", Name = "123" });
            //throw new ApplicationException("测试工作单元");
            var result = await base.InsertAsync(dto);

            await _distributedEventBus.PublishAsync(new AppCreateEventData
            {
                Id = 1,
                Name = "222"
            });

            return result;
        }

        public async Task<ResultDto<List<WmsMaterialImportOutput>>> Import(Stream fileStream)
        {

            _excelService.LoadWorkbook(fileStream);

            var importInputList = _excelService.ReadListByNameManager<WmsMaterialImportInput>(0);



            var importResultTemplateAbsoluteFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, WmsMaterialConst.导入结果模板路径);
            var importResultRelativeFileDir = $"{WmsMaterialConst.导入结果保存目录}{DateTime.Now.ToString("yyyy/MM/dd") }";
            var importResultAbsoluteFileDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, importResultRelativeFileDir);
            importResultAbsoluteFileDir.CreateDirectory();
            var importResultFileName = $"{WmsMaterialConst.导入结果文件名称 }{Guid.NewGuid()}.xlsx";
            var importResultRelativeFilePath = $"{ importResultRelativeFileDir.TrimEnd('/') }/{importResultFileName}";
            var importResultAbsoluteFilePath = $"{ importResultAbsoluteFileDir.TrimEnd('/') }/{importResultFileName}";
            _excelService.WriteListByNameManager(importResultTemplateAbsoluteFilePath, importResultAbsoluteFilePath, importInputList);

            return new ResultDto<List<WmsMaterialImportOutput>>(new List<WmsMaterialImportOutput>());
        }


        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="fileStream"></param>
        /// <returns></returns>
        public async Task<ResultDto<object>> ImportAsync(Stream fileStream)
        {
            _excelService.LoadWorkbook(fileStream);

            var importInputList = _excelService.ReadListByNameManager<WmsMaterialOfWarehouseImportInput>(0);

            List<WmsMaterialOfWarehouseImportOutput> outputList = new List<WmsMaterialOfWarehouseImportOutput>();
            outputList.Add(new WmsMaterialOfWarehouseImportOutput
            {
                 ImportResult="成功",
                  IsVirtual=false,
                   MaterialCode="xxx",
                    Qty=717,
                     Sloc="合格",
                      WarehouseCode="xxx",
            });


            //写入导出结果
            var importResultTemplateAbsoluteFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, WmsMaterialOfWarehouseConsts.导入结果模板路径);
            var importResultRelativeFileDir = $"{WmsMaterialOfWarehouseConsts.导入结果保存目录}{DateTime.Now.ToString("yyyy/MM/dd") }";
            var importResultAbsoluteFileDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, importResultRelativeFileDir);
            importResultAbsoluteFileDir.CreateDirectory();
            var importResultFileName = $"{WmsMaterialOfWarehouseConsts.导入结果文件名称 }{Guid.NewGuid()}.xlsx";
            var importResultRelativeFilePath = $"{ importResultRelativeFileDir.TrimEnd('/') }/{importResultFileName}";
            var importResultAbsoluteFilePath = $"{ importResultAbsoluteFileDir.TrimEnd('/') }/{importResultFileName}";
            _excelService.WriteListByNameManager(importResultTemplateAbsoluteFilePath, importResultAbsoluteFilePath, outputList);

            return new ResultDto<object>((object)importResultRelativeFilePath);

        }
    }
}
